package com.nq.utils.task.tsanghi;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.nq.common.ExchangeEnum;
import com.nq.common.entity.*;
import com.nq.common.entity.info.StStockIntroductionInfo;
import com.nq.common.entity.info.StockTickerListInfo;
import com.nq.common.entity.info.UsIndexTickerInfo;
import com.nq.common.entity.vo.StStockOnlyMarketAndCode;
import com.nq.common.entity.vo.StStockTickerDetailsVo;
import com.nq.dao.StThirdInterfaceStatisticsMapper;
import com.nq.dao.stock.StStockIntroductionMapper;
import com.nq.stock.entity.StStockIntroduction;
import com.nq.stock.entity.StStockKLine;
import com.nq.stock.service.IStIpoService;
import com.nq.stock.service.IStNewsService;
import com.nq.stock.service.IStStockService;
import com.nq.stock.service.IStStockTickerService;
import com.nq.utils.HttpClientRequest;
import com.nq.utils.redis.RedisShardedPoolUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.*;

/**
 * 获取股票数据
 */
@Component
@Slf4j
public class StocksComponent {

    @Value("${stocks.common_url}")
    private String stockUrl;
    // 财务数据
    @Value("${stocks.intro_url}")
    private String introUrl;

    @Value("${spring.profiles.active}")
    private String active;

    @Resource
    private IStStockService stStockService;
    @Resource
    private IStStockTickerService stStockTickerService;
    @Resource
    private StStockIntroductionMapper stStockIntroductionMapper;
    @Resource
    private IStNewsService stNewsService;
    @Resource
    private StThirdInterfaceStatisticsMapper thirdInterfaceStatisticsMapper;
    @Resource
    private IStIpoService stIpoService;

    // 获取产品列表
    public static final String ALL_SYMBOL = "all_symbol";
    // 全市场报价
    public static final String PRICES = "prices";
    // 单个/多个符号完整行情
    public static final String MINI_PRICES = "mini_prices";
    // 单个/多个符号实时K线
    public static final String MINI_LISTS = "mini_lists";
    // 单个历史K线
    public static final String MINI_LIST = "mini_list";
    // 新闻
    public static final String NEWS_PAGE = "news_page";
    // IPO
    public static final String IPO_LIST = "ipo_list";
    // 财务数据
    public static final String PROFILE = "profile";

    //SH指数交易所代码
    public static final String HOSEIN = "HOSEIN";

    // 指数
    public static final String HOSEIN_VN30_INDEX = "VN30";

    public static final String HOSEIN_HNXINDEX_INDEX = "HNXINDEX";

    public static final String HOSEIN_VNINDEX_INDEX = "VNINDEX";


    // 股票redis Key
    public static final String STOCK_REDIS_KEY = "stock:";
    // 股票K线
    public static final String STOCK_LINE_REDIS_KEY = "stockLine:";



    /**
     * 获取上海交易所产品列表
     */
//    @PostConstruct
//    @Scheduled(cron = "0 10 18 * * ?")
//    public void getNSEStockData(){
//
//        String url = stockUrl + ALL_SYMBOL + "?market=" + ExchangeEnum.SH.getExchangeCode();
//        try {
//            String result = HttpClientRequest.doGet(url);
//            List<StockList> stockResult = JSON.parseArray(result, StockList.class);
//            stStockService.addStockList(stockResult);
//        } catch (Exception e) {
//            log.error("获取上海交易所产品列表失败", e);
//        }
//
//    }
    /**
     * 获取深圳交易所产品列表
     */
//    @PostConstruct
//    @Scheduled(cron = "0 20 18 * * ?")
//    public void getBSEStockData(){
//
//        String url = stockUrl + ALL_SYMBOL + "?market=" + ExchangeEnum.SZ.getExchangeCode();
//        try {
//            String result = HttpClientRequest.doGet(url);
//            List<StockList> stockResult = JSON.parseArray(result, StockList.class);
//            stStockService.addStockList(stockResult);
//        } catch (Exception e) {
//            log.error("获取深圳交易所产品列表失败", e);
//        }
//
//    }

    /**
     * 获取北京证券交易所产品列表
     */
//    @PostConstruct
//    @Scheduled(cron = "0 10 4 * * ?")
//    public void getNYSEStockData(){
//
//        String url = stockUrl + ALL_SYMBOL + "?market=" + ExchangeEnum.BJ.getExchangeCode();
//        try {
//            String result = HttpClientRequest.doGet(url);
//            List<StockList> stockResult = JSON.parseArray(result, StockList.class);
//            stStockService.addStockList(stockResult);
//        } catch (Exception e) {
//            log.error("获取北京证券交易所产品列表失败", e);
//        }
//
//    }


    /**
     * 全量更新所有股票的实时行情
     */
//    @PostConstruct
    @Scheduled(cron = "0 0/2 * * * ?")
    public void getAllMarketPrices(){
        log.info("==============开始执行======全量更新所有股票的实时行情===========");
        long start = System.currentTimeMillis();
        try {
            // SH交易所数据
            String nseUrl = stockUrl + PRICES + "?market=" + ExchangeEnum.HOSEIN.getExchangeCode();
            String nseResult = HttpClientRequest.doGet(nseUrl);
            List<StockTickerList> nseStockTickerList = JSON.parseArray(nseResult, StockTickerList.class);

            String nseKey = STOCK_REDIS_KEY + ExchangeEnum.HOSEIN.getExchangeCode();
            RedisShardedPoolUtils.setEx(nseKey, JSON.toJSONString(nseStockTickerList), 30);

            // SZ交易所数据
            String bseUrl = stockUrl + PRICES + "?market=" + ExchangeEnum.HNX.getExchangeCode();
            String bseResult = HttpClientRequest.doGet(bseUrl);
            List<StockTickerList> bseStockTickerList = JSON.parseArray(bseResult, StockTickerList.class);

            String bseKey = STOCK_REDIS_KEY + ExchangeEnum.HNX.getExchangeCode();
            RedisShardedPoolUtils.setEx(bseKey, JSON.toJSONString(bseStockTickerList), 30);

            // BJ交易所数据
            String nyseUrl = stockUrl + PRICES + "?market=" + ExchangeEnum.UPCOM.getExchangeCode();
            String nyseResult = HttpClientRequest.doGet(nyseUrl);
            List<StockTickerList> nyseStockTickerList = JSON.parseArray(nyseResult, StockTickerList.class);

            String nyseKey = STOCK_REDIS_KEY + ExchangeEnum.UPCOM.getExchangeCode();
            RedisShardedPoolUtils.setEx(nyseKey, JSON.toJSONString(nyseStockTickerList), 30);

        } catch (Exception e) {
            log.error("全量更新所有股票的实时行情失败", e);
        }
        log.info("==============执行结束======全量更新所有股票的实时行情===========");
        long end = System.currentTimeMillis();
        log.info("==============执行时间===============" + (end - start) / 1000 + "秒");

    }
    /**
     * 获取SH交易所产品全市场报价  北京时间17.31分执行
     */

//    @PostConstruct
    @Scheduled(cron = "0 33 13 * * MON-FRI")
    public void getNSEStockPrice(){

        String url = stockUrl + PRICES + "?market=" + ExchangeEnum.HOSEIN.getExchangeCode();

        try {
            String result = HttpClientRequest.doGet(url);
            List<StockTickerList> stockTickerList = JSON.parseArray(result, StockTickerList.class);
            stStockTickerService.addStockTicker(stockTickerList);

            // thirdInterfaceStatistic(PRICES, "getNSEStockPrice");
        } catch (Exception e) {
            log.error("获取HOSEIN交易所产品全市场报价失败", e);
        }

    }
    /**
     * 获取SZ交易所产品全市场报价 北京时间17.32分执行
     */

//    @PostConstruct  // 或者在程序启动时手动调用执行任务的方法
    @Scheduled(cron = "0 35 13 * * MON-FRI")
    public void getBSEStockPrice(){

        String url = stockUrl + PRICES + "?market=" + ExchangeEnum.HNX.getExchangeCode();

        try {
            String result = HttpClientRequest.doGet(url);
            List<StockTickerList> stockTickerList = JSON.parseArray(result, StockTickerList.class);
            stStockTickerService.addStockTicker(stockTickerList);

            // thirdInterfaceStatistic(PRICES, "getBSEStockPrice");
        } catch (Exception e) {
            log.error("获取HNX交易所产品全市场报价失败", e);
        }

    }
    /**
     * 获取BJ证券交易所产品全市场报价  北京时间凌晨4.01分执行
     */

//    @PostConstruct  // 或者在程序启动时手动调用执行任务的方法
    @Scheduled(cron = "0 5 4 * * MON-FRI")
    public void getNYSEStockPrice(){

        String url = stockUrl + PRICES + "?market=" + ExchangeEnum.UPCOM.getExchangeCode();

        try {
            String result = HttpClientRequest.doGet(url);
            List<StockTickerList> stockTickerList = JSON.parseArray(result, StockTickerList.class);
            stStockTickerService.addStockTicker(stockTickerList);

            // thirdInterfaceStatistic(PRICES, "getNYSEStockPrice");
        } catch (Exception e) {
            log.error("获取UPCOM证券交易所产品全市场报价失败", e);
        }

    }

    /**
     * 获取新闻列表
     */
    @PostConstruct
    @Scheduled(cron = "0 30 * * * ?")
    public void getNews(){

        ArrayList<String> countryList = new ArrayList<>();
        countryList.add("vietnam");
        try {
            for (String country : countryList) {
                String url = stockUrl + NEWS_PAGE + "?country=" + country + "&page=1";

                String result = HttpClientRequest.doGet(url);

                NewsList news = JSON.parseObject(result, NewsList.class);
                stNewsService.addNews(news);

                // thirdInterfaceStatistic(NEWS_PAGE, "getNews");
            }

        } catch (Exception e) {
            log.error("获取新闻列表失败", e);
        }

    }


    /**
     * 查询指数K线
     * @param market
     * @param code
     * @param interval
     * @param page
     * @return
     */
    public List<StStockTickerKLineList> queryIndexKLineDetailsByMarketAndCode(String market, String code, String interval, String page){

        List<StStockTickerKLineList> info = new ArrayList<>();
        try {
            log.info("获取根据市场和股票编码查询K线数据,参数：market={}, code={}, interval={}.", market, code, interval );
            String url = stockUrl + MINI_LISTS + "?market=" + URLEncoder.encode(market, "utf8")
                    + "&symbol=" + URLEncoder.encode(code, "utf8")
                    + "&interval=" + URLEncoder.encode(interval, "utf8")
                    + "&page=" + URLEncoder.encode(page, "utf8");

            String result = HttpClientRequest.doGet(url);

            info = JSON.parseArray(result, StStockTickerKLineList.class);
            if (null != info && info.size() > 0) {

               // 不在交易时间内 K线数据可能为空，所以要保证数据不为空
                for (StStockTickerKLineList kLineList : info) {
                    String data = kLineList.getData();
                    if (StringUtils.isBlank(data)) {
                        StStockKLine kLine = stStockTickerService.queryKLineByMarketAndCode(market, code);
                        if (null != kLine) {
                            kLineList.setData(kLine.getData());
                        }
                    }else {
                        // 将数据存入数据库
                        String listMarket = kLineList.getMarket();
                        String listCode = kLineList.getCode();

                        StStockKLine oldKLine = stStockTickerService.queryKLineByMarketAndCode(listMarket, listCode);
                        StStockKLine kLine = new StStockKLine();
                        BeanUtils.copyProperties(kLineList, kLine);
                        if (null == oldKLine) {
                            stStockTickerService.addStockKLine(kLine);
                        }else {
                            stStockTickerService.updateStockKLineById(kLine);
                        }
                    }
                }
                return info;
            }
        } catch (Exception e) {
            log.info("获取根据市场和股票编码查询K线数据异常,参数：market={}, code={}, interval={}.", market, code, interval );
            // 从数据库中取
            List<StStockKLine> kLines = stStockTickerService.queryKLineByMarket(market);
            for (StStockKLine kLine : kLines) {
                StStockTickerKLineList tickerKLineList = new StStockTickerKLineList();
                BeanUtils.copyProperties(kLine, tickerKLineList);
                info.add(tickerKLineList);
            }
            return info;
        }
        return null;
    }


    /**
     * 获取IPO列表
     */
//     @PostConstruct
//    @Scheduled(cron = "0 0 0,12 * * ?")
    public void getIPO(){

        try {
            String url = stockUrl + IPO_LIST + "?country=india";
            String result = HttpClientRequest.doGet(url);

            IpoList ipos = JSON.parseObject(result, IpoList.class);
            stIpoService.addIpo(ipos);
        } catch (Exception e) {
            log.error("获取IPO列表失败", e);
        }

    }

    /**
     * 定时删除K线异常的股票
     */
//    @PostConstruct
    @Scheduled(cron = "0 0 0,12 * * ?")
    public void deleteKLineError(){
        try {
           List<StStockOnlyMarketAndCode> list = stStockTickerService.selectOnlyMarketAndCode();
           for (StStockOnlyMarketAndCode stock : list) {
               String market = stock.getMarket();
               String code = stock.getCode();
               StStockTickerKLineList kLineList = this.queryKLineDetailsByMarketAndCode(market, code, "1day", "1");
               // this.thirdInterfaceStatistic(StocksComponent.MINI_LIST, "deleteKLineError");

               if (null != kLineList) {
                   String data = kLineList.getData();
                   if (StringUtils.isNotBlank(data)) {
                       String[] splitData = data.split(";");
                       List<String> dataList = Arrays.asList(splitData);
                       if (dataList.size() < 10) {
                           // 需要删除对应的股票信息
                           stStockTickerService.deleteByMarketAndCode(market, code);
                       }
                   }

               }

           }

        } catch (Exception e) {
            log.error("定时删除K线异常的股票失败", e);
        }

    }

    /**
     * 查询股票实时数据
     * @param market
     * @param codes
     */
    public List<StockTickerListInfo> queryRealTimeData(String market, String codes){
        List<StockTickerListInfo> info  = new ArrayList<>();
        try {
            String url = stockUrl + MINI_PRICES + "?market=" + URLEncoder.encode(market, "utf8") + "&symbol=" + URLEncoder.encode(codes, "utf8");
            String result = HttpClientRequest.doGet(url);
            List<StStockTickerDetails> stStockTickerDetails = JSON.parseArray(result, StStockTickerDetails.class);
            for (StStockTickerDetails details : stStockTickerDetails) {
                StockTickerListInfo data = details.getData();
                data.setCode(details.getCode());
                info.add(data);
            }

            return info;
        } catch (Exception e) {
            log.error("股票数据定时刷新失败", e);
        }
        return info;
    }

    /**
     * 根据市场和股票编码查询详情
     */
    public StStockTickerDetails queryDetailsByMarketAndCode(String market, String code){

        StStockTickerDetails stockTickerDetails = new StStockTickerDetails();

        try {
            // 指数需要单独处理
            if (market.equals("USIN")) {
                String url = stockUrl + MINI_PRICES + "?" + "market=" + URLEncoder.encode(market, "utf8") + "&symbol=" + URLEncoder.encode(code, "utf8");

                String result = HttpClientRequest.doGet(url);
                List<StUsIndexTicker> info = JSON.parseArray(result, StUsIndexTicker.class);

                if (null != info && info.size() > 0) {
                    StUsIndexTicker tickerInfo = info.get(0);
                    UsIndexTickerInfo data = tickerInfo.getData();
                    StockTickerListInfo listInfo = new StockTickerListInfo();
                    listInfo.setPrice(new BigDecimal(data.getPrice()));
                    listInfo.setUp(new BigDecimal(data.getUp()));
                    listInfo.setChange(new BigDecimal(data.getChange()));

                    stockTickerDetails.setData(listInfo);
                    stockTickerDetails.setCode(tickerInfo.getCode());
                    stockTickerDetails.setMarket(tickerInfo.getMarket());
                    stockTickerDetails.setStatus(tickerInfo.getStatus());
                    stockTickerDetails.setMessage(tickerInfo.getMessage());
                    return stockTickerDetails;
                }
            }else {
                String marketRedisKey = STOCK_REDIS_KEY + market;

                String url = stockUrl + MINI_PRICES + "?" + "market=" + URLEncoder.encode(market, "utf8") + "&symbol=" + URLEncoder.encode(code, "utf8");

                String result = HttpClientRequest.doGet(url);
                List<StStockTickerDetails> info = JSON.parseArray(result, StStockTickerDetails.class);

                if (null != info && info.size() > 0) {
                    stockTickerDetails = info.get(0);

                    StockTickerListInfo data = stockTickerDetails.getData();
                    String detailsCode = stockTickerDetails.getCode();
                    if (null != data && StringUtils.isNotBlank(detailsCode)) {
                        data.setCode(detailsCode);
                    }

                    RedisShardedPoolUtils.set(marketRedisKey, JSON.toJSONString(stockTickerDetails));
                    return stockTickerDetails;
                }else {
                    StStockTickerDetailsVo tickerDetailsVo = stStockTickerService.assembleTheStockDetailData(market, code);
                    if (null != tickerDetailsVo) {
                        return tickerDetailsVo;
                    }else {
                        return stockTickerDetails;
                    }
                }
                // 先从redis中查

//                String redisData = RedisShardedPoolUtils.get(marketRedisKey);
//                List<StockTickerList> stockTickerList = JSON.parseArray(redisData, StockTickerList.class);
//                if (null != stockTickerList && !stockTickerList.isEmpty()) {
//                    // 使用 Stream 进行过滤和查找
//                    Optional<StockTickerList> result = stockTickerList.stream()
//                            .filter(stock -> code.equals(stock.getCode()))  // 根据 code 进行过滤
//                            .findFirst();  // 查找第一个匹配的元素
//
//                    // 如果找到了符合条件的 StockTickerList 对象，则打印或进一步处理
//                    StStockTickerDetails details = new StStockTickerDetails();
//                    result.ifPresent(stock -> {
//                        System.out.println("Redis中找到符合条件的股票信息：" + stock);
//                        // 可以进一步处理找到的股票信息
//                        details.setMarket(market);
//                        details.setCode(code);
//                        details.setMessage("");
//                        details.setData(stock.getMsg());
//                    });
//
//                    // 如果没有找到符合条件的 StockTickerList 对象，可以输出相应信息
//                    if (!result.isPresent()) {
//                        System.out.println("Redis中没有找到符合条件的股票信息, 查找第三方实时接口");
//                        String url = stockUrl + MINI_PRICES + "?market=" + market + "&symbol=" + code;
//                        String result1 = HttpClientRequest.doGet(url);
//                        List<StStockTickerDetails> info = JSON.parseArray(result1, StStockTickerDetails.class);
//                        if (null != info && info.size() > 0) {
//                            stockTickerDetails = info.get(0);
//                            return stockTickerDetails;
//                        }else {
//                            return null;
//                        }
//                    }
//
//                    return details;
//                }else {
//                    String url = stockUrl + MINI_PRICES + "?market=" + market + "&symbol=" + code;
//                    String result = HttpClientRequest.doGet(url);
//                    List<StStockTickerDetails> info = JSON.parseArray(result, StStockTickerDetails.class);
//                    if (null != info && info.size() > 0) {
//                        stockTickerDetails = info.get(0);
//
//                        RedisShardedPoolUtils.setEx(marketRedisKey, JSON.toJSONString(stockTickerDetails), 1);
//                        return stockTickerDetails;
//                    }
//                }
            }

        } catch (Exception e) {
            log.error("根据市场和股票编码查询详情失败,参数：market={}, code={} . 开始查询redis", market, code );

            // 从redis中取
            String marketRedisKey = STOCK_REDIS_KEY + market;
            if (!RedisShardedPoolUtils.exists(marketRedisKey)) {
                StStockTickerDetailsVo tickerDetailsVo = stStockTickerService.assembleTheStockDetailData(market, code);
                if (null != tickerDetailsVo) {
                    return tickerDetailsVo;
                }else {
                    return stockTickerDetails;
                }
            }
            String redisData = RedisShardedPoolUtils.get(marketRedisKey);
            if (StringUtils.isBlank(redisData)) {
                StStockTickerDetailsVo tickerDetailsVo = stStockTickerService.assembleTheStockDetailData(market, code);
                if (null != tickerDetailsVo) {
                    return tickerDetailsVo;
                }else {
                    return stockTickerDetails;
                }
            }
            StStockTickerDetails stStockTickerDetails = JSON.parseObject(redisData, StStockTickerDetails.class);
            ArrayList<StStockTickerDetails> stockTickerList = new ArrayList<>();
            stockTickerList.add(stStockTickerDetails);

            if (null != stockTickerList && !stockTickerList.isEmpty()) {
                // 使用 Stream 进行过滤和查找
                Optional<StStockTickerDetails> result = stockTickerList.stream()
                        .filter(stock -> code.equals(stock.getCode()))  // 根据 code 进行过滤
                        .findFirst();  // 查找第一个匹配的元素

                // 如果找到了符合条件的 StockTickerList 对象，则打印或进一步处理
                StStockTickerDetails details = new StStockTickerDetails();
                result.ifPresent(stock -> {
                    System.out.println("找到符合条件的股票信息：" + stock);
                    // 可以进一步处理找到的股票信息
                    details.setMarket(market);
                    details.setCode(code);
                    details.setMessage("");
                    details.setData(stock.getData());
                });

                // 如果没有找到符合条件的 StockTickerList 对象，可以输出相应信息
                if (!result.isPresent()) {
                    System.out.println("最后也没没有找到符合条件的股票信息，查数据库");

                    StStockTickerDetailsVo tickerDetailsVo = stStockTickerService.assembleTheStockDetailData(market, code);
                    if (null != tickerDetailsVo) {
                        return tickerDetailsVo;
                    }else {
                        return stockTickerDetails;
                    }
                }
                return details;
            }
        }
        return stockTickerDetails;
    }

    private static String encodeUrl(String url) throws UnsupportedEncodingException {
        String[] parts = url.split("\\?");
        if (parts.length == 2) {
            String baseUrl = parts[0];
            String query = parts[1];
            String[] params = query.split("&");
            StringBuilder encodedQuery = new StringBuilder();
            for (String param : params) {
                String[] keyValue = param.split("=");
                if (keyValue.length == 2) {
                    encodedQuery.append(URLEncoder.encode(keyValue[0], "UTF-8"))
                            .append("=")
                            .append(URLEncoder.encode(keyValue[1], "UTF-8"))
                            .append("&");
                }
            }
            if (encodedQuery.length() > 0) {
                encodedQuery.setLength(encodedQuery.length() - 1); // Remove trailing '&'
            }
            return baseUrl + "?" + encodedQuery.toString();
        }
        return url; // No query parameters to encode
    }
    /**
     * 根据市场和股票编码查询K线数据
     */
    public StStockTickerKLineList queryKLineDetailsByMarketAndCode(String market, String code, String interval, String page){


        StStockTickerKLineList tickerKLineList = new StStockTickerKLineList();
        String redisKey = STOCK_LINE_REDIS_KEY + market + "_" + code;
//
//        if (!RedisShardedPoolUtils.exists(redisKey)) {
//            StStockKLine kLine = stStockTickerService.queryKLineByMarketAndCode(market, code);
//            if (null == kLine) {
//                return tickerKLineList;
//            }
//        }
//        String redisObj = RedisShardedPoolUtils.get(redisKey);
//        if (StringUtils.isBlank(redisObj)) {
//            StStockKLine kLine = stStockTickerService.queryKLineByMarketAndCode(market, code);
//            if (null == kLine) {
//                return tickerKLineList;
//            }
//        }
//        StStockTickerKLineList kLineList1 = JSON.parseObject(redisObj, StStockTickerKLineList.class);
//        if (null != kLineList1) {
//            log.info("股票K线数据从redis获取成功, redisKey: {}", redisKey);
//            return kLineList1;
//        }

        try {
            String url = stockUrl + MINI_LIST + "?market=" + URLEncoder.encode(market, "utf8") + "&symbol=" + URLEncoder.encode(code, "utf8") + "&interval=" + URLEncoder.encode(interval, "utf8") + "&page=" + URLEncoder.encode(page, "utf8");
            String result = HttpClientRequest.doGet(url);
            StStockTickerKLineList kLineList = JSON.parseObject(result, StStockTickerKLineList.class);

            if (null != kLineList) {
                BeanUtils.copyProperties(kLineList, tickerKLineList);

                // 不在交易时间内 K线数据可能为空，所以要保证数据不为空
                String kLineListData = tickerKLineList.getData();
                if (StringUtils.isBlank(kLineListData)) {
                    // 从数据库中取
                    StStockKLine kLine = stStockTickerService.queryKLineByMarketAndCode(market, code);
                    if (null != kLine) {
                        BeanUtils.copyProperties(kLine, tickerKLineList);
                        return tickerKLineList;
                    }
                }

                // 放入redis, 设置有效时间
                RedisShardedPoolUtils.setEx(redisKey, JSON.toJSONString(kLineList),  1);
                log.info("股票K线数据放入redis成功, redisKey: {}", redisKey);

                // 将数据存入数据库
                StStockKLine oldKLine = stStockTickerService.queryKLineByMarketAndCode(market, code);
                StStockKLine kLine = new StStockKLine();
                BeanUtils.copyProperties(tickerKLineList, kLine);
                if (null == oldKLine) {
                    stStockTickerService.addStockKLine(kLine);
                }else {
                    stStockTickerService.updateStockKLineById(kLine);
                }

                return tickerKLineList;
            }else {
                // 从数据库中取
                StStockKLine kLine = stStockTickerService.queryKLineByMarketAndCode(market, code);
                if (null != kLine) {
                    BeanUtils.copyProperties(kLine, tickerKLineList);
                    return tickerKLineList;
                }
            }
        } catch (Exception e) {
            // 从数据库中取
            StStockKLine kLine = stStockTickerService.queryKLineByMarketAndCode(market, code);
            if (null == kLine) {
                return tickerKLineList;
            }
            BeanUtils.copyProperties(kLine, tickerKLineList);
            log.error("获取根据市场和股票编码查询K线数据失败,参数：market={}, code={} .", market, code );
        }
        return tickerKLineList;
    }

    public static void main(String[] args) {
        StockList list = new StockList();
        list.setStatus(0);

        System.out.println(list.getStatus() ==null );
    }

    public StStockIntroduction queryStockIntroductionByMarketAndCode(String market, String symbol) {
        log.info("查询财务数据：market={},symbol={}", market, symbol);

        // 从数据库中查询是否有该数据
        QueryWrapper<StStockIntroduction> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("market", market);
        queryWrapper.eq("symbol", symbol);
        StStockIntroduction introduction = stStockIntroductionMapper.selectOne(queryWrapper);

        if (null == introduction) {

            try {
                // 调第三方接口查询
                String url = introUrl + PROFILE + "?market=" + URLEncoder.encode(market, "utf8") + "&symbol=" + URLEncoder.encode(symbol, "utf8");
                String result = HttpClientRequest.doGet(url);
                StStockIntroductionData stStockIntroduction = JSON.parseObject(result, StStockIntroductionData.class);

                if (null != stStockIntroduction) {
                    StStockIntroductionInfo data = stStockIntroduction.getData();
                    if(null == data){
                        return null;
                    }
                    StStockIntroduction introductionParam = new StStockIntroduction();
                    BeanUtils.copyProperties(data, introductionParam);
                    introductionParam.setMarket(market);
                    introductionParam.setSymbol(symbol);
                    stStockIntroductionMapper.insert(introductionParam);
                    // 返回新增的数据
                    return introductionParam;
                }

            } catch (Exception e) {
                log.error("查询财务数据失败,参数：market={}, symbol={} .", market, symbol );
                return null;
            }
        }

        return introduction;
    }

//    public void thirdInterfaceStatistic(String source, String methods){
//        StThirdInterfaceStatistics statistics = new StThirdInterfaceStatistics();
//        statistics.setSource(source);
//        statistics.setMethods(methods);
//        statistics.setCreateTime(new Date());
//        thirdInterfaceStatisticsMapper.insert(statistics);
//    }
}
